<?php

/**
 * Class YRegionValidator
 */
class YRegionValidator extends CValidator
{
	public $regionAttribute;

	public $allowEmpty = false;

	protected function validateAttribute($object, $attribute)
	{
		$value = $object->$attribute;

		if ($this->regionAttribute == null) {
			$this->regionAttribute = $attribute;
		}

		if (!$this->allowEmpty && $this->isEmpty($value)) {
			$this->addError($object, $this->regionAttribute, Yii::t('yii', '{attribute} cannot be blank.'));
		}

		if ($attribute === 'province') {
			$exists = Yii::app()->region->exists($value, 0);
		} elseif ($attribute === 'city') {
			$exists = (!empty($object->province)) && Yii::app()->region->exists($value, $object->province);
		} elseif ($attribute === 'county') {
			$exists = (!empty($object->city)) && Yii::app()->region->exists($value, $object->city);
		} else {
			$exists = false;
		}

		if ($exists === false) {
			$this->addError($object, $this->regionAttribute, Yii::t('yii', '{attribute} cannot be blank.'));
		}
	}

	public function clientValidateAttribute($object, $attribute)
	{
		$message = $this->message;
		$attribute = $this->regionAttribute;

		if (!$this->allowEmpty) {
			if ($message === null)
				$message = Yii::t('yii', '{attribute} cannot be blank.');
			$message = strtr($message, array(
				'{attribute}' => $object->getAttributeLabel($attribute),
			));

			$emptyCondition = "jQuery.trim(value)==''";
			return "
if({$emptyCondition}) {
	messages.push(" . CJSON::encode($message) . ");
}
";
		}
	}
}